package com.future.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.future.allUtils.enums.RoleEnum;
import com.future.allUtils.enums.TargetTypeEnum;
import com.future.allUtils.utils.CacheClient;
import com.future.allUtils.utils.RegexPatterns;
import com.future.allUtils.utils.SecurityUtils;
import com.future.domain.*;
import com.future.domain.DTO.*;
import com.future.domain.StudentClassAuthentication;
import com.future.domain.vo.CheckIsLikeVO;
import com.future.domain.vo.CollectionTargetVO;
import com.future.domain.vo.LikeTargetVO;
import com.future.domain.vo.StudentClassVO;
import com.future.mapper.*;
import com.future.service.NotificationService;
import com.future.service.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.models.auth.In;
import kotlin.jvm.internal.Lambda;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.future.allUtils.constants.RedisCacheConstants.*;
import static com.future.allUtils.constants.RedisConstants.LOGIN_USER_KEY;
import static com.future.allUtils.constants.RedisConstants.LOGIN_USER_TTL;
import static com.future.allUtils.utils.RegexPatterns.*;
import static com.future.service.Impl.MediaResourceServiceImpl.CACHE_MEDIA_INFO_KEY;


@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private CacheClient cacheClient;
    @Autowired
    private CertificationMapper certificationMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private LikeMapper likeMapper;
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private CollectionMapper collectionMapper;
    @Autowired
    private StudentClassMapper studentClassMapper;
    @Autowired
    private StudentClassAuthenticationMapper studentClassAuthenticationMapper;
    @Autowired
    private UserClassMapper userClassMapper;
    @Autowired
    private NotificationService notificationService;
    @Autowired
    private PsychologicalKnowledgeMapper psychologicalKnowledgeMapper;
    @Autowired
    private MediaResourceMapper mediaResourceMapper;
    @Autowired
    private FollowMapper followMapper;
    private UserDetailsServiceAutoConfiguration userDetailsServiceAutoConfiguration;


    @Override
    public Result deleteAccount(UserLoginDTO dto) {
        User user = SecurityUtils.getCurrentUser().getUser();
        if(user==null){
            return Result.fail("请先登录");
        }


        //邮箱格式校验
        if(!dto.getEmail().matches(EMAIL_REGEX)){
            return Result.fail("邮箱格式有误");
        }


        //校验验证码
        String captcha = stringRedisTemplate.opsForValue().get(CAPTCHA_PREFIX + dto.getEmail());
        if(!StringUtils.hasText(captcha)){
            return Result.fail("验证码错误");
        }
        if(!captcha.equals(dto.getCaptcha())){
            return Result.fail("验证码错误");
        }


        //逻辑删除用户 status=3
        user.setStatus(3);
        user.setAccount(String.valueOf(user.getId()));
        user.setEmail(String.valueOf(user.getId()));
        int i = userMapper.updateById(user);

        //删除redis信息
        cacheClient.deleteByPattern(LOGIN_USER_KEY + user.getId());
        cacheClient.deleteByPattern(USER_INFO_PREFIX + user.getId());
        return i>0?Result.ok():Result.fail("注销失败");
    }

    //用户申请成为老师、心理医生
    public Result roleCertification(RoleCertificationDTO dto) {

        //1.表单详细身份填写
        User user = SecurityUtils.getCurrentUser().getUser();
        if(user==null){
            return Result.fail("请重新登录");
        }

        //2.校验
        if(!dto.getIdCard().matches(RegexPatterns.ID_CARD_REGEX)){
            return Result.fail("身份证号格式有误");
        }
        if(!dto.getPhone().matches(RegexPatterns.PHONE_REGEX)){
            return Result.fail("手机号格式有误");
        }

        RoleEnum role = RoleEnum.getByRoleName(dto.getRole());
        if (role==null){
            return Result.fail("请选择正确的身份");
        }

        Certification certification = new Certification();
        certification.setUserId(user.getId());
        certification.setRole(dto.getRole());
        certification.setRealName(dto.getRealName());
        certification.setIdCard(dto.getIdCard());
        certification.setPhone(dto.getPhone());
        certification.setAddress(dto.getAddress());

        LambdaQueryWrapper<Certification> lqw=new LambdaQueryWrapper<>();
        lqw.eq(Certification::getUserId,user.getId());
        lqw.eq(Certification::getRole,dto.getRole());
        if(certificationMapper.selectOne(lqw)!=null){
            return Result.fail("请勿重复申请");
        }
        try {
            //2.数据库插入申请信息
            certificationMapper.insert(certification);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }


        return Result.ok();
    }

    @Override
    public Result getUserInfo(Long userId) {

        // 使用缓存工具类查询用户信息（解决缓存穿透）
        UserDTO userDTO = cacheClient.queryWithPassThrough(
                "user:info:vo:",  // 缓存键前缀
                userId,         // 唯一标识（用户ID）
                UserDTO.class,  // 目标类型
                // 数据库查询逻辑：根据ID查询并转换为UserDTO
                id -> {
                    User user = userMapper.selectById(id);
                    if (user == null) {
                        return null; // 数据库不存在时返回null，触发缓存空值
                    }
                    // 转换User为UserDTO
                    UserDTO dto = new UserDTO();
                    dto.setAccount(user.getAccount());
                    dto.setEmail(user.getEmail());
                    List<Integer> roleIds = userMapper.getUserRole(user.getId());

                    if (roleIds != null && !roleIds.isEmpty()) {
                        // 转换所有角色ID为角色名称
                        List<String> roleNames = new ArrayList<>();
                        for (Integer roleId : roleIds) {
                            RoleEnum roleEnum = RoleEnum.getByRoleId(roleId);
                            if (roleEnum != null) {
                                roleNames.add(roleEnum.getRoleName());
                            }
                        }
                        dto.setRoles(roleNames);
                    }

                    StudentClassVO studentClass = studentClassMapper.selectStudentClass(user.getId());
                    if (studentClass != null){
                        dto.setStudentClass(studentClass.getStudentClass());
                        dto.setStudentClassId(studentClass.getClassID());
                    }else{
                        dto.setStudentClass("未加入班级");
                        dto.setStudentClassId(null);
                    }
                    dto.setAvatar(user.getAvatar());
                    dto.setUsername(user.getUsername());
                    dto.setGender(user.getGender());
                    dto.setBio(user.getBio());
                    dto.setStatus(user.getStatus());
                    dto.setIsCertified(user.getIsCertified());
                    dto.setLastLoginAt(String.valueOf(user.getLastLoginAt()));
                    dto.setCreatedAt(String.valueOf(user.getCreatedAt()));
                    dto.setUpdatedAt(String.valueOf(user.getUpdatedAt()));
                    dto.setAddress(user.getAddress());
                    dto.setId(userId);
                    dto.setIdStr(String.valueOf(userId));
                    return dto;
                },
                30L,  // 基础过期时间30分钟
                TimeUnit.MINUTES
        );

        if (userDTO == null) {
            return Result.fail("用户不存在或已注销");
        }
        return Result.ok(userDTO);
    }




    @Override
        public Result updatePassword(PasswordDTO  dto) {
        //1.校验邮箱格式
        if(!StringUtils.hasText(dto.getEmail())){
            return Result.fail("邮箱不能为空");
        }
        if(!StringUtils.hasText(dto.getCaptcha())){
            return Result.fail("验证码错误");
        }
        if (!dto.getEmail().matches(EMAIL_REGEX)){
            System.out.println(dto.getEmail()+"666");
            return Result.fail("邮箱格式有误");
        }


        //校验邮箱
        LoginUserDetails currentUser = SecurityUtils.getCurrentUser();
        User user = currentUser.getUser();
        if(!dto.getEmail().equals(user.getEmail())){
            System.out.println(dto.getEmail());
            System.out.println(user.getEmail());
            return Result.fail("邮箱错误");
        }

        String cacheCode = stringRedisTemplate.opsForValue().get(CAPTCHA_PREFIX+ dto.getEmail());
        //校验验证码
        if (!StringUtils.hasText(cacheCode)) {
            return Result.fail("验证码不存在或已过期");
        }
        if (!cacheCode.equals(dto.getCaptcha())) {
            return Result.fail("验证码错误");
        }


        //校验新密码格式
        if(!dto.getNewPassword().matches(RegexPatterns.PASSWORD_REGEX)){
            return Result.fail("密码格式有误,应为8-20位，包含大小写字母、数字和特殊符号（!@#$%^&*）" );
        }

        user.setPassword(bCryptPasswordEncoder.encode(dto.getNewPassword()));
        userMapper.updateById(user);
        currentUser.setUser(user);
       cacheClient.set(LOGIN_USER_KEY+user.getId(),currentUser,cacheClient.randomObjectTimes(LOGIN_USER_TTL), TimeUnit.SECONDS);

        return Result.ok("密码修改成功");
    }


    /**
     * 点赞（这是可以不同类型点赞的，需要typeId转typeName）
     * 分两步1.处理不含表名_like_count冗余字段的表
     * 直接insert就行
     *      2.处理包含表名_like_count冗余字段的表
 *      先insert，然后要update->like_count+1, 不过要使用乐观锁考虑并发问题
     */
    @Override
    @Transactional
    public Result like(LikeDTO dto) {
        // 获取当前用户ID
        Long userId = SecurityUtils.getCurrentUser().getUser().getId();
        if (userId == null) {
            return Result.fail("请先登录");
        }

        // 类型id转名称
        TargetTypeEnum value = TargetTypeEnum.getTargetTypeById(dto.getTargetTypeId());
        if (value != null) {
            dto.setTargetType(value.getTargetTypeName());
        } else {
            return Result.fail("请选择正确的点赞对象");
        }

        // 1. 查询是否存在点赞记录（包括已删除的）
        LambdaQueryWrapper<Like> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Like::getUserId, userId)
                .eq(Like::getTargetId, dto.getTargetId())
                .eq(Like::getTargetType, dto.getTargetType());

        Like existingLike = likeMapper.selectOne(lqw);

        // 2. 处理已存在的记录
        if (existingLike != null) {
            // 2.1 已存在有效点赞（未删除）
            if (existingLike.getIsDeleted() == 0) {
                return Result.fail("请勿重复点赞");
            }
            // 2.2 存在已删除的点赞记录，进行恢复
            else {
                existingLike.setIsDeleted(0);
                existingLike.setCreatedAt(LocalDateTime.now());
                int update = likeMapper.updateById(existingLike);
                if (update != 1) {
                    throw new RuntimeException("恢复点赞记录失败");
                }
                if(existingLike.getTargetType().equals("文章")) {
                    Article article = articleMapper.selectById(existingLike.getTargetId());
                    if (article != null) {
                        Long authorId = article.getAuthorId();
                        notificationService.sendLike(authorId, existingLike.getTargetId(), "点赞了你的文章");
                    }
                }else if(existingLike.getTargetType().equals("评论")) {
                    Comment comment = commentMapper.selectById(existingLike.getTargetId());
                    if (comment != null) {
                        Long userId1 = comment.getUserId();
                        notificationService.sendLike(userId1, existingLike.getTargetId(), "点赞了你的评论");
                    }
                }else if(existingLike.getTargetType().equals("心理知识"))
                {
                    PsychologicalKnowledge psychologicalKnowledge = psychologicalKnowledgeMapper.selectById(existingLike.getTargetId());
                    if(psychologicalKnowledge!=null)
                    {
                        Long authorId = psychologicalKnowledge.getAuthorId();
                        notificationService.sendLike(authorId,existingLike.getTargetId(),"点赞了你的心理知识");
                    }
                }else if (existingLike.getTargetType().equals("媒体资源")){
                    MediaResource mediaResource = mediaResourceMapper.selectById(existingLike.getTargetId());
                    if (mediaResource!=null){
                        Long authorId = mediaResource.getUploaderId();
                        notificationService.sendLike(authorId,existingLike.getTargetId(),"点赞了你的媒体资源");
                    }
                }
            }
        }
        // 3. 完全不存在记录，新增点赞
        else {
            Like like = new Like();
            like.setTargetId(dto.getTargetId());
            like.setTargetType(dto.getTargetType());
            like.setUserId(userId);
            like.setCreatedAt(LocalDateTime.now());
            like.setIsDeleted(0); // 新增时默认未删除
            int insert = likeMapper.insert(like);
            if (insert != 1) {
                throw new RuntimeException("点赞记录插入失败");
            }
            System.out.println(TargetTypeEnum.ARTICLE);
            if(like.getTargetType().equals("文章"))
            {
                Article article = articleMapper.selectById(like.getTargetId());
                if(article!=null) {
                    Long authorId = article.getAuthorId();
                    notificationService.sendLike(authorId, like.getTargetId(), "点赞了你的文章");
                }
            }else if(like.getTargetType().equals("评论"))
            {
                Comment comment = commentMapper.selectById(like.getTargetId());
                if(comment!=null) {
                    Long userId1 = comment.getUserId();
                    notificationService.sendLike(userId1, like.getTargetId(), "点赞了你的评论");
                }
            }else if(like.getTargetType().equals("心理知识")) {
                PsychologicalKnowledge psychologicalKnowledge = psychologicalKnowledgeMapper.selectById(like.getTargetId());
                if (psychologicalKnowledge != null) {
                    Long authorId = psychologicalKnowledge.getAuthorId();
                    notificationService.sendLike(authorId, like.getTargetId(), "点赞了你的心理知识");
                }
            }else if(like.getTargetType().equals("媒体资源")){
                MediaResource mediaResource = mediaResourceMapper.selectById(like.getTargetId());
                if (mediaResource != null) {
                    Long authorId = mediaResource.getUploaderId();
                    notificationService.sendLike(authorId,like.getTargetId(),"点赞了你的媒体资源");
                }
            }
        }

        // 4. 乐观锁更新目标对象的点赞数（无论新增还是恢复，都需要+1）
        try {
            if ("文章".equals(dto.getTargetType())) {
                Article article = articleMapper.selectById(dto.getTargetId());
                if (article == null) {
                    throw new RuntimeException("点赞的文章不存在");
                }

                int rows = articleMapper.updateLikeCount(
                        dto.getTargetId(),
                        article.getLikeCount(),
                        article.getLikeCount() + 1
                );
                cacheClient.deleteByPattern("article:detail:"+dto.getTargetId());
                if (rows == 0) {
                    throw new RuntimeException("点赞数更新失败，请重试");
                }
            } else if ("评论".equals(dto.getTargetType())) {
                Comment comment = commentMapper.selectById(dto.getTargetId());
                if (comment == null) {
                    throw new RuntimeException("评论不存在");
                }

                int rowC = commentMapper.updateLikeCount(
                        comment.getId(),
                        comment.getLikeCount(),
                        comment.getLikeCount() + 1
                );
                if (rowC == 0) {
                    throw new RuntimeException("点赞数更新失败，请重试");
                }
            }else if ("媒体资源".equals(dto.getTargetType())){
                MediaResource mediaResource = mediaResourceMapper.selectById(dto.getTargetId());
                if (mediaResource == null) {
                    throw new RuntimeException("媒体资源不存在");
                }

                int rowM = mediaResourceMapper.updateLikeCount(
                        mediaResource.getId(),
                        mediaResource.getLikeCount(),
                        mediaResource.getLikeCount() + 1
                );
                cacheClient.deleteByPattern(CACHE_MEDIA_INFO_KEY + mediaResource.getId());

            }else if ("心理知识".equals(dto.getTargetType())){
                PsychologicalKnowledge psychologicalKnowledge = psychologicalKnowledgeMapper.selectById(dto.getTargetId());
                if (psychologicalKnowledge == null) {
                    throw new RuntimeException("心理知识不存在");
                }
                int rowP = psychologicalKnowledgeMapper.updateLikeCount( psychologicalKnowledge.getId(),
                        psychologicalKnowledge.getLikeCount(),
                        psychologicalKnowledge.getLikeCount() + 1);
                cacheClient.deleteByPattern(PSYCHOLOGICAL_KNOWLEDGE_PREFIX+psychologicalKnowledge.getId());
            }
            cacheClient.deleteByPattern("user:info:vo" + userId);
            cacheClient.deleteByPattern("user:like:list:" + userId + ":*");
            return Result.ok("点赞成功");
        } catch (DuplicateKeyException e) {
            // 并发导致的异常，返回友好提示并重新抛出异常
            log.error("重复点赞", e);
            throw new RuntimeException("请勿重复点赞"); // 抛出异常触发回滚
        } catch (RuntimeException e) {
            log.error("点赞业务异常", e);
            throw e; // 重新抛出保留原始异常信息
        } catch (Exception e) {
            log.error("点赞失败", e);
            throw new RuntimeException("点赞失败，请稍后重试");
        }
    }


    @Override
    @Transactional
    public Result cancelLike(LikeDTO dto) {
        // 获取当前用户ID
        Long userId = SecurityUtils.getCurrentUser().getUser().getId();
        if (userId == null) {
            return Result.fail("请先登录");
        }

        // 类型id转名称
        TargetTypeEnum value = TargetTypeEnum.getTargetTypeById(dto.getTargetTypeId());
        if (value != null) {
            dto.setTargetType(value.getTargetTypeName());
        } else {
            return Result.fail("请选择正确的取消赞对象");
        }

        // 1. 查询当前用户的有效点赞记录
        LambdaQueryWrapper<Like> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Like::getUserId, userId)
                .eq(Like::getTargetId, dto.getTargetId())
                .eq(Like::getTargetType, dto.getTargetType())
                .eq(Like::getIsDeleted, 0);

        Like existingLike = likeMapper.selectOne(lqw);
        if (existingLike == null) {
            return Result.fail("尚未点赞，无法取消点赞");
        }

        // 2. 执行取消点赞操作
        try {
            // 2.1 逻辑删除点赞记录
            Like like = new Like();
            like.setId(existingLike.getId());
            like.setIsDeleted(1);
            like.setCreatedAt(LocalDateTime.now()); // 更新时间

            int update = likeMapper.updateById(like);
            if (update != 1) {
                throw new RuntimeException("取消点赞失败，记录更新异常");
            }

            // 2.2 更新目标对象的点赞数
            if ("文章".equals(dto.getTargetType())) {
                Article article = articleMapper.selectById(dto.getTargetId());
                if (article == null) {
                    throw new RuntimeException("取消点赞的文章不存在");
                }

                if (article.getLikeCount() <= 0) {
                    throw new RuntimeException("点赞数异常，无法取消点赞");
                }

                int rows = articleMapper.updateLikeCount(
                        dto.getTargetId(),
                        article.getLikeCount(),
                        article.getLikeCount() - 1
                );
                cacheClient.deleteByPattern("article:detail:"+dto.getTargetId());
                if (rows == 0) {
                    throw new RuntimeException("点赞数更新失败，请重试");
                }
            } else if ("评论".equals(dto.getTargetType())) {
                Comment comment = commentMapper.selectById(dto.getTargetId());
                if (comment == null) {
                    throw new RuntimeException("评论不存在");
                }

                if (comment.getLikeCount() <= 0) {
                    throw new RuntimeException("点赞数异常，无法取消点赞");
                }

                int rowC = commentMapper.updateLikeCount(
                        comment.getId(),
                        comment.getLikeCount(),
                        comment.getLikeCount() - 1
                );
                if (rowC == 0) {
                    throw new RuntimeException("点赞数更新失败，请重试");
                }
            }else if("媒体资源".equals(dto.getTargetType())){
                MediaResource mediaResource = mediaResourceMapper.selectById(dto.getTargetId());
                if (mediaResource == null) {
                    throw new RuntimeException("媒体资源不存在");
                }
                if (mediaResource.getLikeCount() <= 0) {
                    throw new RuntimeException("点赞数异常，无法取消点赞");
                }
                int rowM = mediaResourceMapper.updateLikeCount(
                        mediaResource.getId(),
                        mediaResource.getLikeCount(),
                        mediaResource.getLikeCount() - 1
                );
                cacheClient.deleteByPattern(CACHE_MEDIA_INFO_KEY + mediaResource.getId());
            }else if ("心理知识".equals(dto.getTargetType())){
                PsychologicalKnowledge psychologicalKnowledge = psychologicalKnowledgeMapper.selectById(dto.getTargetId());
                if (psychologicalKnowledge == null) {
                    throw new RuntimeException("心理知识不存在");
                }
                if (psychologicalKnowledge.getLikeCount() <= 0){
                    throw new RuntimeException("点赞数异常，无法取消点赞");
                }
                int rowP = psychologicalKnowledgeMapper.updateLikeCount( psychologicalKnowledge.getId(),
                        psychologicalKnowledge.getLikeCount(),
                        psychologicalKnowledge.getLikeCount() - 1);
                if (rowP == 0) {
                    throw new RuntimeException("点赞数更新失败，请重试");
                }
                cacheClient.deleteByPattern(PSYCHOLOGICAL_KNOWLEDGE_PREFIX+psychologicalKnowledge.getId());
            }
            cacheClient.deleteByPattern("user:info:vo" + userId);
            cacheClient.deleteByPattern("user:like:list:" + userId + ":*");
            return Result.ok("取消点赞成功");
        } catch (RuntimeException e) {
            // 业务逻辑异常
            throw new RuntimeException("取消点赞失败");
        } catch (Exception e) {
            // 未知异常
            log.error("取消点赞失败", e);
           throw new RuntimeException("取消点赞失败，请稍后重试");
        }
    }



    /**
     *获取用户点赞记录
     *分类讨论targetTypeId--->targetTypeName
     * 用一个带Page<>连表查询就行了
     */
    @Override
    public Result getUserLikeList(LikeDTO dto, Integer pageNum, Integer pageSize) {
        // 1. 校验用户登录状态
        Long userId = SecurityUtils.getCurrentUser().getUser().getId();
        if (userId == null) {
            return Result.fail("请先登录");
        }

        // 2. 转换目标类型（id -> 名称）
        TargetTypeEnum target = TargetTypeEnum.getTargetTypeById(dto.getTargetTypeId());
        if (target == null) {
            return Result.fail("不存在该点赞类型");
        }
        String targetType = target.getTargetTypeName();

        // 3. 处理分页参数
        pageNum = (pageNum == null || pageNum < 1) ? 1 : pageNum;
        pageSize = (pageSize == null || pageSize < 1) ? 10 : pageSize;

        // 4. 构建缓存键（包含分页参数，保证缓存粒度）
        String cacheKeyPrefix = "user:like:list:" + userId + ":" + targetType + ":";

        // 5. 使用缓存工具类查询（解决缓存穿透+雪崩）
        PageDTO<LikeTargetVO> pageDTO = cacheClient.queryWithPassThrough(
                cacheKeyPrefix,
                pageNum + ":" + pageSize,  // 分页参数作为ID，确保唯一
                PageDTO.class,
                // 数据库查询逻辑
                pageParams -> {
                    // 解析分页参数
                    String[] params = pageParams.split(":");
                    int pn = Integer.parseInt(params[0]);
                    int ps = Integer.parseInt(params[1]);

                    Page<LikeTargetVO> page = new Page<>(pn, ps);
                    Page<LikeTargetVO> resultPage = null;
                    if ("文章".equals(targetType)){
                       resultPage=likeMapper.selectLikeArticleList(page, userId);
                    }else if ("媒体资源".equals(targetType)){
                       resultPage=likeMapper.selectLikeMediaResourceList(page, userId);
                    }

                    if (resultPage == null){
                        return null;
                    }
                    return PageDTO.pageConvert(resultPage);
                },
                5L,  // 短期缓存5分钟（点赞记录变更频率中等）
                TimeUnit.MINUTES
        );

        if (pageDTO == null) {
            // 缓存穿透：返回空分页
            return Result.ok(new PageDTO<>());
        }
        return Result.ok(pageDTO);
    }

    /**
     * 收藏功能实现
     */
    @Override
    @Transactional
    public Result collection(CollectionDTO dto) {
        // 获取当前用户ID
        Long userId = SecurityUtils.getCurrentUser().getUser().getId();
        if (userId == null) {
            return Result.fail("请先登录");
        }

        // 类型id转名称
        TargetTypeEnum value = TargetTypeEnum.getTargetTypeById(dto.getTargetTypeId());
        if (value != null) {
            dto.setTargetType(value.getTargetTypeName());
        } else {
            return Result.fail("请选择正确的收藏对象");
        }

        // 1. 查询是否存在收藏记录（包括已删除的）
        LambdaQueryWrapper<Collection> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Collection::getUserId, userId)
                .eq(Collection::getTargetId, dto.getTargetId())
                .eq(Collection::getTargetType, dto.getTargetType());

        Collection existingCollection = collectionMapper.selectOne(lqw);

        // 2. 处理已存在的记录
        if (existingCollection != null) {
            // 2.1 已存在有效收藏（未删除）
            if (existingCollection.getIsDeleted() == 0) {
                return Result.fail("请勿重复收藏");
            }
            // 2.2 存在已删除的收藏记录，进行恢复
            else {
                existingCollection.setIsDeleted(0);
                existingCollection.setCreatedAt(LocalDateTime.now());
                int update = collectionMapper.updateById(existingCollection);
                if (update != 1) {
                    throw new RuntimeException("恢复收藏记录失败");
                }
                if(existingCollection.getTargetType().equals("文章")) {
                    Article article = articleMapper.selectById(existingCollection.getTargetId());
                    if (article != null) {
                        Long authorId = article.getAuthorId();
                        notificationService.sendMark(authorId, existingCollection.getTargetId(), "收藏了你的文章");
                    }
                }else if(existingCollection.getTargetType().equals("心理知识"))
                {
                    PsychologicalKnowledge psychologicalKnowledge = psychologicalKnowledgeMapper.selectById(existingCollection.getTargetId());
                    if(psychologicalKnowledge!=null) {
                        Long authorId = psychologicalKnowledge.getAuthorId();
                        notificationService.sendMark(authorId, existingCollection.getTargetId(), "收藏了你的心理知识");
                    }

                }else if (existingCollection.getTargetType().equals("媒体资源"))
                {
                    MediaResource mediaResource = mediaResourceMapper.selectById(existingCollection.getTargetId());
                    if(mediaResource!=null) {
                        Long authorId = mediaResource.getUploaderId();
                        notificationService.sendMark(authorId, existingCollection.getTargetId(), "收藏了你的媒体资源");
                    }
                }
            }
            }
        // 3. 完全不存在记录，新增收藏
        else {
            Collection collection = new Collection();
            collection.setTargetId(dto.getTargetId());
            collection.setTargetType(dto.getTargetType());
            collection.setUserId(userId);
            collection.setCreatedAt(LocalDateTime.now());
            collection.setIsDeleted(0); // 新增时默认未删除
            int insert = collectionMapper.insert(collection);
            if (insert != 1) {
                throw new RuntimeException("收藏记录插入失败");
            }
            if(collection.getTargetType().equals("文章"))
            {
                Article article = articleMapper.selectById(collection.getTargetId());
                if(article!=null) {
                    Long authorId = article.getAuthorId();
                    notificationService.sendMark(authorId, collection.getTargetId(), "收藏了你的文章");

                }
            }else if(collection.getTargetType().equals("心理知识"))
                {
                PsychologicalKnowledge psychologicalKnowledge = psychologicalKnowledgeMapper.selectById(collection.getTargetId());
                if(psychologicalKnowledge!=null) {
                    Long authorId = psychologicalKnowledge.getAuthorId();
                    notificationService.sendMark(authorId, collection.getTargetId(), "收藏了你的心理知识");
                }
            }else if (collection.getTargetType().equals("媒体资源"))
                {
                MediaResource mediaResource = mediaResourceMapper.selectById(collection.getTargetId());
                if(mediaResource!=null) {
                    Long authorId = mediaResource.getUploaderId();
                    notificationService.sendMark(authorId, collection.getTargetId(), "收藏了你的媒体资源");
                }
            }
        }

        try {
            if("文章".equals(value.getTargetTypeName())){
                Article article = articleMapper.selectById(dto.getTargetId());
                if (article == null){
                    return Result.fail("文章不存在");
                }
                int row = articleMapper.updateCollectionCount(dto.getTargetId(),
                        article.getCollectionCount(),
                        article.getCollectionCount() + 1);

                if (row == 0){
                    throw new RuntimeException("收藏数更新失败，请重试");
                }
                cacheClient.deleteByPattern("article:detail:"+dto.getTargetId());
            }else if ("媒体资源".equals(value.getTargetTypeName())){
                MediaResource mediaResource = mediaResourceMapper.selectById(dto.getTargetId());
                if (mediaResource == null){
                    return Result.fail("媒体资源不存在");
                }
                int row = mediaResourceMapper.updateCollectionCount(dto.getTargetId(),
                        mediaResource.getCollectionCount(),
                        mediaResource.getCollectionCount() + 1);

                if (row == 0) {
                    throw new RuntimeException("收藏数更新失败，请重试");
                }
                cacheClient.deleteByPattern(CACHE_MEDIA_INFO_KEY + mediaResource.getId());
            }else if ("心理知识".equals(value.getTargetTypeName())){
                PsychologicalKnowledge psychologicalKnowledge = psychologicalKnowledgeMapper.selectById(dto.getTargetId());
                if (psychologicalKnowledge == null){
                    return Result.fail("心理知识不存在");
                }
                int row = psychologicalKnowledgeMapper.updateCollectionCount(dto.getTargetId(),
                        psychologicalKnowledge.getCollectionCount(),
                        psychologicalKnowledge.getCollectionCount() + 1);
                if (row == 0) {
                    throw new RuntimeException("收藏数更新失败，请重试");
                }
                cacheClient.deleteByPattern(PSYCHOLOGICAL_KNOWLEDGE_PREFIX+psychologicalKnowledge.getId());
            }
        } catch (DuplicateKeyException e) {
            // 并发导致的异常，返回友好提示并重新抛出异常
            log.error("重复点赞", e);
            throw new RuntimeException("请勿重复点赞"); // 抛出异常触发回滚
        } catch (RuntimeException e) {
            log.error("点赞业务异常", e);
            throw e;
        } catch (Exception e) {
            log.error("点赞失败", e);
            throw new RuntimeException("点赞失败，请稍后重试");
        }
        cacheClient.deleteByPattern("user:info:vo" + userId);
        cacheClient.deleteByPattern("user:collection:list:" + userId + ":*");
        return Result.ok("收藏成功");
    }

    /**
     * 取消收藏功能实现
     */
    @Override
    @Transactional
    public Result cancelCollection(CollectionDTO dto) {
        // 获取当前用户ID
        Long userId = SecurityUtils.getCurrentUser().getUser().getId();
        if (userId == null) {
            return Result.fail("请先登录");
        }

        // 类型id转名称
        TargetTypeEnum value = TargetTypeEnum.getTargetTypeById(dto.getTargetTypeId());
        if (value != null) {
            dto.setTargetType(value.getTargetTypeName());
        } else {
            return Result.fail("请选择正确的取消收藏对象");
        }

        // 1. 查询当前用户的有效收藏记录
        LambdaQueryWrapper<Collection> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Collection::getUserId, userId)
                .eq(Collection::getTargetId, dto.getTargetId())
                .eq(Collection::getTargetType, dto.getTargetType())
                .eq(Collection::getIsDeleted, 0);

        Collection existingCollection = collectionMapper.selectOne(lqw);
        if (existingCollection == null) {
            return Result.fail("尚未收藏，无法取消收藏");
        }

        // 2. 执行取消收藏操作
        try {
            // 2.1 逻辑删除收藏记录
            Collection collection = new Collection();
            collection.setId(existingCollection.getId());
            collection.setIsDeleted(1);
            collection.setCreatedAt(LocalDateTime.now()); // 更新时间

            int update = collectionMapper.updateById(collection);
            if (update != 1) {
                throw new RuntimeException("取消收藏失败，记录更新异常");
            }

            // 2.2 更新目标对象的收藏数
            if ("文章".equals(dto.getTargetType())) {
                Article article = articleMapper.selectById(dto.getTargetId());
                if (article == null) {
                    throw new RuntimeException("取消收藏的文章不存在");
                }

                if (article.getCollectionCount() <= 0) {
                    throw new RuntimeException("收藏数异常，无法取消收藏");
                }

                int rows = articleMapper.updateCollectionCount(
                        dto.getTargetId(),
                        article.getCollectionCount(),
                        article.getCollectionCount() - 1
                );
                if (rows == 0) {
                    throw new RuntimeException("收藏数更新失败，请重试");
                }
                cacheClient.deleteByPattern("article:detail:"+dto.getTargetId());
            }else if ("媒体资源".equals(dto.getTargetType())){
                MediaResource mediaResource = mediaResourceMapper.selectById(dto.getTargetId());
                if (mediaResource == null) {
                    throw new RuntimeException("取消收藏的媒体资源不存在");
                }
                if (mediaResource.getCollectionCount() <= 0) {
                    throw new RuntimeException("收藏数异常，无法取消收藏");
                }
                int rows = mediaResourceMapper.updateCollectionCount(dto.getTargetId(),
                        mediaResource.getCollectionCount(),
                        mediaResource.getCollectionCount() - 1);

                if (rows == 0) {
                    throw new RuntimeException("收藏数更新失败，请重试");
                }
                cacheClient.deleteByPattern(CACHE_MEDIA_INFO_KEY + mediaResource.getId());
            }else if ("心理知识".equals(dto.getTargetType())){
                PsychologicalKnowledge psychologicalKnowledge = psychologicalKnowledgeMapper.selectById(dto.getTargetId());
                if (psychologicalKnowledge == null) {
                    throw new RuntimeException("取消收藏的心理知识不存在");
                }
                if (psychologicalKnowledge.getCollectionCount() <= 0) {
                    throw new RuntimeException("收藏数异常，无法取消收藏");
                }
                int rows = psychologicalKnowledgeMapper.updateCollectionCount(dto.getTargetId(),
                        psychologicalKnowledge.getLikeCount(),
                        psychologicalKnowledge.getLikeCount()-1);
                cacheClient.deleteByPattern(PSYCHOLOGICAL_KNOWLEDGE_PREFIX+psychologicalKnowledge.getId());
            }
            cacheClient.deleteByPattern("user:info:vo" + userId);
            cacheClient.deleteByPattern("user:collection:list:" + userId + ":*");
            return Result.ok("取消收藏成功");
        } catch (RuntimeException e) {
            // 业务逻辑异常
            throw new RuntimeException("取消收藏失败,请重试");
        } catch (Exception e) {
            // 未知异常
            log.error("取消收藏失败，请重试", e);
            throw new RuntimeException("取消收藏失败，请稍后重试");
        }
    }

    /**
     * 获取用户收藏记录
     */
    @Override
    public Result getUserCollectionList(CollectionDTO dto, Integer pageNum, Integer pageSize) {
        // 1. 校验登录状态
        Long userId = SecurityUtils.getCurrentUser().getUser().getId();
        if (userId == null) {
            return Result.fail("请先登录");
        }

        // 2. 转换目标类型
        TargetTypeEnum target = TargetTypeEnum.getTargetTypeById(dto.getTargetTypeId());
        if (target == null) {
            return Result.fail("不存在该收藏类型");
        }
        String targetType = target.getTargetTypeName();

        // 3. 处理分页参数
        pageNum = (pageNum == null || pageNum < 1) ? 1 : pageNum;
        pageSize = (pageSize == null || pageSize < 1) ? 10 : pageSize;

        // 4. 构建缓存键
        String cacheKeyPrefix = "user:collection:list:" + userId + ":" + targetType + ":";

        // 5. 缓存查询
        PageDTO<CollectionTargetVO> pageDTO = cacheClient.queryWithPassThrough(
                cacheKeyPrefix,
                pageNum + ":" + pageSize,
                PageDTO.class,
                // 数据库查询逻辑
                pageParams -> {
                    String[] params = pageParams.split(":");
                    int pn = Integer.parseInt(params[0]);
                    int ps = Integer.parseInt(params[1]);

                    Page<CollectionTargetVO> page = new Page<>(pn, ps);
                    Page<CollectionTargetVO> resultPage=null;
                    if ("文章".equals(targetType)){
                        resultPage = collectionMapper.selectCollectionArticleList(page, userId);
                    }else if ("媒体资源".equals(targetType)){
                        resultPage = collectionMapper.selectCollectionMediaResourceList(page, userId);

                    }

                    if (resultPage == null){
                        return null;
                    }

                    PageDTO<CollectionTargetVO> vo = new PageDTO<>();
                    vo.setRows(resultPage.getRecords());
                    vo.setTotal(resultPage.getTotal());
                    vo.setTotalPage(resultPage.getPages());
                    return vo;
                },
                5L,  // 缓存5分钟
                TimeUnit.MINUTES
        );

        if (pageDTO == null) {
            return Result.ok(new PageDTO<>());
        }
        return Result.ok(pageDTO);
    }

    @Override
    public Result joinClass(StudentClassAuthenticationDTO dto) {
        //校验是否已经有班级
        Long studentId = SecurityUtils.getCurrentUser().getUser().getId();
        LambdaQueryWrapper<UserClass> userClassQuery = new LambdaQueryWrapper<>();
        userClassQuery.eq(UserClass::getUserId, studentId);
        UserClass userClass = userClassMapper.selectOne(userClassQuery);
        if (userClass != null) {
            return Result.fail("只能加入一个班级");
        }
        // 1. 判断班级是否存在
        LambdaQueryWrapper<StudentClass> classQuery = new LambdaQueryWrapper<>();
        classQuery.eq(StudentClass::getClassName, dto.getClassName());
        StudentClass studentClass = studentClassMapper.selectOne(classQuery);
        if (studentClass == null) {
            return Result.fail("班级不存在");
        }

        // 2. 校验班级是否已分配教师
        Long teacherId = studentClass.getTeacherId();
        if (teacherId == null) {
            return Result.fail("班级未分配班主任，无法申请加入");
        }

        // 3. 校验是否已申请过该班级
        LambdaQueryWrapper<StudentClassAuthentication> authQuery = new LambdaQueryWrapper<>();
        authQuery.eq(StudentClassAuthentication::getStudentId, studentId)
                .eq(StudentClassAuthentication::getStatus, "待审核")
                .eq(StudentClassAuthentication::getApplyType,"加入");
        StudentClassAuthentication existingAuth = studentClassAuthenticationMapper.selectOne(authQuery);
        if (existingAuth != null) {
            return Result.fail("您已申请加入过班级，请勿重复提交");
        }

        // 4. 创建新的申请记录
        StudentClassAuthentication authentication = new StudentClassAuthentication();
        authentication.setStudentId(studentId);
        authentication.setClassId(studentClass.getId());
        authentication.setApplicationReason(dto.getApplicationReason());
        authentication.setReviewerId(teacherId);
        authentication.setApplyType("加入");

        int insert = studentClassAuthenticationMapper.insert(authentication);
        //删除redis缓存
        cacheClient.deleteByPattern("user:class:list:" + studentId+":*");
        return insert == 1 ? Result.ok("申请成功") : Result.fail("申请失败");
    }

    @Override
    public Result getStudentClass(Integer pageNum, Integer pageSize) {
        // 1. 参数校验
        pageNum = (pageNum == null || pageNum < 1) ? 1 : pageNum;
        pageSize = (pageSize == null || pageSize < 1) ? 10 : pageSize;

        // 2. 获取用户ID
        Long userId = SecurityUtils.getCurrentUser().getUser().getId();
        if (userId == null) {
            return Result.fail("请先登录");
        }

        // 3. 构建缓存键
        String cacheKeyPrefix = "user:class:list:" + userId + ":";

        // 4. 缓存查询（班级信息变更频率低，缓存1小时）
        PageInfo<StudentClassVO> pageInfo = cacheClient.queryWithPassThrough(
                cacheKeyPrefix,
                pageNum + ":" + pageSize,
                PageInfo.class,
                // 数据库查询逻辑
                pageParams -> {
                    String[] params = pageParams.split(":");
                    int pn = Integer.parseInt(params[0]);
                    int ps = Integer.parseInt(params[1]);

                    PageHelper.startPage(pn, ps);
                    List<StudentClassVO> list = studentClassMapper.selectAllStudentClass(userId);
                    return new PageInfo<>(list);
                },
                60L,  // 缓存1小时（班级信息低频变更）
                TimeUnit.MINUTES
        );

        if (pageInfo == null) {
            return Result.ok(new PageInfo<>());
        }
        return Result.ok(pageInfo);
    }


    @Override
    public Result cancelJoinClass() {
        //校验是否存在申请
        Long studentId = SecurityUtils.getCurrentUser().getUser().getId();
        LambdaQueryWrapper<StudentClassAuthentication> lqw=new LambdaQueryWrapper<>();
        lqw.eq(StudentClassAuthentication::getStudentId,studentId)
                        .eq(StudentClassAuthentication::getStatus,"待审核")
                         .eq(StudentClassAuthentication::getApplyType,"加入");
        StudentClassAuthentication studentClassAuthentication = studentClassAuthenticationMapper.selectOne(lqw);
        if (studentClassAuthentication==null){
            return Result.fail("没有申请加入的班级");
        }
        int delete = studentClassAuthenticationMapper.delete(lqw);
        //删除redis缓存
        cacheClient.deleteByPattern("user:class:list:" + studentId+":*");
        return delete==1?Result.ok("取消成功"):Result.fail("取消失败");
    }

    @Override
    public Result quitClass(StudentClassAuthenticationDTO dto) {
        //校验是否已经加入班级
        Long studentId = SecurityUtils.getCurrentUser().getUser().getId();
        LambdaQueryWrapper<UserClass> lqw=new LambdaQueryWrapper<>();
        lqw.eq(UserClass::getUserId,studentId);
        UserClass userClass = userClassMapper.selectOne(lqw);
        if (userClass==null){
            return Result.fail("没有加入的班级");
        }

        LambdaQueryWrapper<StudentClass> classQuery = new LambdaQueryWrapper<>();
        classQuery.eq(StudentClass::getId, userClass.getClassId());
        StudentClass studentClass = studentClassMapper.selectOne(classQuery);

        // 2. 校验班级是否已分配教师
        Long teacherId = studentClass.getTeacherId();
        if (teacherId == null) {
            return Result.fail("班级未分配班主任，无法申请加入");
        }

        // 3. 校验是否已申请过该班级
        LambdaQueryWrapper<StudentClassAuthentication> authQuery = new LambdaQueryWrapper<>();
        authQuery.eq(StudentClassAuthentication::getStudentId, studentId)
                .eq(StudentClassAuthentication::getClassId, studentClass.getId())
                .eq(StudentClassAuthentication::getStatus, "待审核")
                .eq(StudentClassAuthentication::getApplyType,"退出");
        StudentClassAuthentication existingAuth = studentClassAuthenticationMapper.selectOne(authQuery);
        if (existingAuth != null) {
            return Result.fail("您已申请退出该班级，请勿重复提交");
        }


        // 4. 创建新的申请记录
        StudentClassAuthentication authentication = new StudentClassAuthentication();
        authentication.setStudentId(studentId);
        authentication.setClassId(studentClass.getId());
        authentication.setApplicationReason(dto.getApplicationReason());
        authentication.setReviewerId(teacherId);
        authentication.setApplyType("退出");

        int insert = studentClassAuthenticationMapper.insert(authentication);
        return insert == 1 ? Result.ok("申请成功") : Result.fail("申请失败");
    }

    @Override
    @Transactional
    public Result updateUser(UserDTO userDTO) {
        // 1. 获取当前登录用户
       LoginUserDetails currentUser =SecurityUtils.getCurrentUser();
       Long userId = currentUser.getUser().getId();

        // 2. 校验用户存在性
      User user = userMapper.selectById(userId);
      if (user==null){
          return Result.fail("用户不存在");
      }
        if (userDTO.getAccount() != null && !userDTO.getAccount().trim().isEmpty()) {
            // 账号格式校验（复用你添加用户时的ACCOUNT_REGEX）
            if (!userDTO.getAccount().matches(ACCOUNT_REGEX)) {
                return Result.fail("账号格式有误，应为6-20位字母、数字、下划线，首位不能为数字");
            }
            //检查新账号是否已被其他用户使用
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getAccount, userDTO.getAccount());
            User existingUser = userMapper.selectOne(queryWrapper);
            if (existingUser != null && !existingUser.getId().equals(userId)) {
                return Result.fail("账号已存在，请更换账号");
            }
            user.setAccount(userDTO.getAccount().trim());
        }
        // 邮箱
        if (userDTO.getEmail() != null && !userDTO.getEmail().trim().isEmpty()) {
            // 邮箱格式校验（使用标准邮箱正则）
            if (!userDTO.getEmail().matches(EMAIL_REGEX)) {
                return Result.fail("邮箱格式不正确");
            }
            // 检查邮箱是否已被其他用户使用
            LambdaQueryWrapper<User> emailWrapper = new LambdaQueryWrapper<>();
            emailWrapper.eq(User::getEmail, userDTO.getEmail().trim());
            User existingEmailUser = userMapper.selectOne(emailWrapper);
            if (existingEmailUser != null && !existingEmailUser.getId().equals(userId)) {
                return Result.fail("该邮箱已被其他账号使用");
            }
            user.setEmail(userDTO.getEmail().trim());
        }

      if (userDTO.getUsername() !=null &&!userDTO.getUsername().trim().isEmpty()){
          if (!userDTO.getUsername().matches(RegexPatterns.USERNAME_REGEX)){
              return Result.fail("用户名格式错误（2-16位，支持汉字、字母、数字、下划线）");
          }
          user.setUsername(userDTO.getUsername());
      }
      if (userDTO.getGender() !=null){
          if (!userDTO.getGender().matches(RegexPatterns.GENDER_CHINESE_REGEX)){
              return Result.fail("性别值必须为“未知”、“男”或“女”");
          }
          user.setGender(userDTO.getGender());
      }
      if (userDTO.getBio()!=null){
          if(userDTO.getBio().length()>500){
              return Result.fail("个人介绍不能超过500个字符");
          }
          user.setBio(userDTO.getBio());
      }
      if (userDTO.getAvatar()!=null){
          if (userDTO.getAvatar().length()>200){
              return Result.fail("头像URL不能超过200个字符");
          }
          user.setAvatar(userDTO.getAvatar());
      }
      if(userDTO.getAddress()!=null&&!userDTO.getAddress().trim().isEmpty()){
//           校验地址格式（1-100位，支持汉字、字母、数字、标点）
        if (!userDTO.getAddress().matches(RegexPatterns.ADDRESS_REGEX)) {
            return Result.fail("地址格式错误（1-100位，支持汉字、字母、数字、常见标点）");
        }
        user.setAddress(userDTO.getAddress().trim());
      }
      user.setUpdatedAt(LocalDateTime.now());
      try {
        userMapper.updateById(user);

        // 6. 清除用户信息缓存（保持缓存一致性）
        cacheClient.deleteByPattern("user:info:vo:" + userId);
        cacheClient.deleteByPattern("user:info:vo:" + userId + ":*");

        return Result.ok("个人信息更新成功");
      } catch (Exception e) {
        log.error("更新个人信息失败", e);
        return Result.fail("更新个人信息失败，请重试");
      }

    }

    @Override
    public Result getTotalCountReceived(Long userId) {
        Long likeCount = likeMapper.selectTotalLikesReceived(userId);
        Long commentCount = commentMapper.selectTotalCommentsReceived(userId);
        Long collectionCount = collectionMapper.selectTotalCollectionsReceived(userId);
        Long followCount = followMapper.getFollowerCount(userId);
        Long fansCount = followMapper.getFollowerCount(userId);
        ReceivedCountDTO receivedCountDTO = new ReceivedCountDTO(likeCount, commentCount, collectionCount, followCount, fansCount);
        return Result.ok(receivedCountDTO);
    }

    @Override
    public Result checkTargetType(Long targetId, Integer targetTypeId) {
        // 参数校验
        if (targetId == null) {
            return Result.fail("目标ID不能为空");
        }
        if (targetTypeId == null) {
            return Result.fail("目标类型ID不能为空");
        }

        TargetTypeEnum targetType = TargetTypeEnum.getTargetTypeById(targetTypeId);
        System.out.println(targetType);
        String targetTypeName = targetType.getTargetTypeName();
        // 检查目标是否存在及获取点赞数和收藏数
        Long likeCount = 0L;
        Long collectionCount = 0L;
        boolean isExists = true;

        // 根据类型ID判断目标类型
        switch (targetTypeId.intValue()) {
            case 1: // 文章
                Article article = articleMapper.selectById(targetId);
                if (article == null) {
                    isExists = false;
                } else {
                    likeCount = article.getLikeCount();
                    collectionCount = article.getCollectionCount();
                }
                break;
            case 2: // 心理知识
                PsychologicalKnowledge knowledge = psychologicalKnowledgeMapper.selectById(targetId);
                if (knowledge == null) {
                    isExists = false;
                } else {
                    likeCount = knowledge.getLikeCount();
                    collectionCount = knowledge.getCollectionCount();
                }
                break;
            case 3: // 媒体资源
                MediaResource media = mediaResourceMapper.selectById(targetId);
                if (media == null) {
                    isExists = false;
                } else {
                    likeCount = media.getLikeCount();
                    collectionCount = media.getCollectionCount();
                }
                break;
            case 4: // 评论
                Comment comment = commentMapper.selectById(targetId);
                if (comment == null) {
                    isExists = false;
                } else {
                    likeCount = comment.getLikeCount();
                    collectionCount = 0L;
                }
                break;
            default:
                return Result.fail("无效的目标类型");
        }

        if (!isExists) {
            return Result.fail("目标不存在");
        }

        // 创建返回对象
        CheckIsLikeVO checkIsLikeVO = new CheckIsLikeVO();
        Long userId = SecurityUtils.getCurrentUserId();

        // 查询是否点赞
        int isLike = likeMapper.selectLikeOrNotByTargetIdAndType(targetId, userId, targetTypeName);
        checkIsLikeVO.setLikeCount(likeCount);
        checkIsLikeVO.setLiked(isLike == 1);
        // 查询是否收藏
        int isCollected = collectionMapper.selectCollectOrNotByTargetIdAndType(targetId, userId, targetTypeName);
        checkIsLikeVO.setCollectionCount(collectionCount);
        checkIsLikeVO.setCollected(isCollected == 1);
        return Result.ok(checkIsLikeVO);
    }
}
